package com.xingkeduo.business.operation.domain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.business.operation.service.ServprodService;
import com.xingkeduo.business.operation.service.ShopsServprodService;
import com.xingkeduo.pojo.dto.Servprod.ServprodMarketDTO;
import com.xingkeduo.pojo.dto.Shops.ShopsServprodDTO;
import com.xingkeduo.pojo.dto.Shops.WebsocketMessageResponse;
import com.xingkeduo.pojo.query.ServprodQuery;
import com.xingkeduo.pojo.query.ShopsServprodQuery;
import com.xingkeduo.pojo.remote.feign.AdminFeignService;
import com.xingkeduo.pojo.remote.feign.MarketingFeignService;
import com.xingkeduo.pojo.table.ServprodTable;
import com.xingkeduo.pojo.table.ShopsServprodTable;
import com.xingkeduo.send.RabbitMqSender;
import com.xingkeduo.tool.AmountUtils;
import com.xingkeduo.tool.CheckDiffListUtils;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.CommonUtil;
import com.xingkeduo.util.tool.IdentityUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.xingkeduo.pojo.dto.Shops.WebsocketMessageResponse.MessageTypeEnum.WORKPAD;

/**
 * 商户domain
 *
 * @author wangxilong <wangxilong@xingkeduo.com>
 * @version id:v0.1 ${date}${time}
 * @package BeautyOS
 * @copyright Copyright (c) XKD 2019
 */
@Component
public class ShopsServprodDomain {

    @Autowired
    private ShopsServprodService shopsServprodService;

    @Autowired
    private ServprodService servprodService;

    @Autowired
    private RabbitMqSender rabbitMqSender;

    @Autowired
    private MarketingFeignService marketingFeignService;

    @Autowired
    private AdminFeignService adminFeignService;

    public ShopsServprodTable getShopsServprodByCode(Long code) throws Throwable {

        ShopsServprodTable shopsServprodTable = shopsServprodService.selectByCode(code);

        return shopsServprodTable;
    }

    /**
     *
     * @param
     * @return 根据店铺ID查询BARBER价格
     * @throws Throwable
     */
    public List<ShopsServprodTable> getBarberPrice(ShopsServprodQuery shopsServprodQuery) throws Throwable {

        if(CommonUtil.isEmpty(shopsServprodQuery.getShopsId())){
            throw new DataException(DataException.Type.DEFAULT, "店铺ID不能为空!");
        }
        List<ShopsServprodTable> shopsServprodTable = shopsServprodService.selectLists(new ShopsServprodQuery().setShopsId(shopsServprodQuery.getShopsId()).setServprodId(Long.valueOf(4)));
        if(!CommonUtil.isEmpty(shopsServprodTable)){
            for (ShopsServprodTable servprodTable : shopsServprodTable) {
                servprodTable.setPrice(Long.valueOf(AmountUtils.changeF2Y(String.valueOf(servprodTable.getPrice()))));
            }
        }else{
            throw new DataException(DataException.Type.DEFAULT, "店铺未配置barber服务或店铺ID不存在!");
        }

        return shopsServprodTable;
    }

    /**
     * 根据店铺ID组装店铺服务价格和营销系统的价格
     */

    public List<ServprodMarketDTO> getOrderPrice(Long shopId) throws Throwable {

        if(CommonUtil.isEmpty(shopId)){
            throw new BusinessException(BusinessException.Type.DEFAULT, "店铺ID不能为空");
        }

        String stringResult = marketingFeignService.getStoreHelpPaymentActivityDetail(shopId);
        if(StringUtils.isBlank(stringResult)){
            throw new BusinessException(BusinessException.Type.DEFAULT, "查询数据为空");
        }

        JSONObject jsonResult =JSON.parseObject(stringResult);
        String status = jsonResult.getOrDefault("status","").toString();
        if(!"1".equals(status)){
            throw new BusinessException(BusinessException.Type.DEFAULT, jsonResult.getOrDefault("msg","").toString());
        }

        List<ShopsServprodTable> shopsServprodTable = shopsServprodService.selectLists(new ShopsServprodQuery().setShopsId(shopId).setServprodId(Long.valueOf(1)));
        String originPrice = "0";
        if(CommonUtil.isEmpty(shopsServprodTable)){
            throw new BusinessException(BusinessException.Type.DEFAULT, "未配置店铺单人剪发价格");
        }
        for (ShopsServprodTable servprodTable : shopsServprodTable) {
            Long price = servprodTable.getPrice();
            originPrice = AmountUtils.changeF2Y(price.toString());
        }
        List<ServprodMarketDTO> responseArray= new ArrayList<>();
        ServprodMarketDTO servprodMarketDTO = new ServprodMarketDTO();
        servprodMarketDTO.setPrice(new BigDecimal(originPrice).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        servprodMarketDTO.setName("原价代购");
        responseArray.add(servprodMarketDTO);
        JSONArray jsonData = jsonResult.getJSONArray("data");
        if(jsonData!= null && jsonData.size()>0){
            int size =jsonData.size();
          for(int i=0;i<size;i++){
              ServprodMarketDTO dto = new ServprodMarketDTO();
              BigDecimal price = BigDecimal.valueOf(0);
              JSONObject jsonObject = jsonData.getJSONObject(i);
              String name =jsonObject.getOrDefault("name","").toString();
              dto.setName(name);
              String marketId =jsonObject.getOrDefault("id","").toString();
              dto.setMarketId(marketId);
              String preferentialMode =jsonObject.getOrDefault("preferentialMode","").toString();
              String activityAmount =jsonObject.getOrDefault("activityAmount","").toString();
              if("0".equals(preferentialMode)){//立减
                   price = new BigDecimal(originPrice).subtract(new BigDecimal(activityAmount)).setScale(2,BigDecimal.ROUND_HALF_UP);
              }
              if("1".equals(preferentialMode)){
                  price = new BigDecimal(originPrice).multiply(new BigDecimal(activityAmount)).setScale(2,BigDecimal.ROUND_HALF_UP);
              }
              if("2".equals(preferentialMode)){
                  price=new BigDecimal(activityAmount);
              }
              dto.setPrice(price.compareTo(BigDecimal.ZERO)<0 ? "0" : price.toString());
              responseArray.add(dto);
          }
        }
        return responseArray;
    }


    public List<ShopsServprodTable> getShopsServprodByShopsId(ShopsServprodQuery shopsServprodQuery) throws Throwable {
        List<ShopsServprodTable> shopsServprodList = new ArrayList<>();
        List<ShopsServprodTable> shopsServprodListTemp = new ArrayList<>();

        if(!CommonUtil.isEmpty(shopsServprodQuery.getShopsId())){
            shopsServprodList  = shopsServprodService.selectLists(shopsServprodQuery);
        }

        ServprodQuery servprodQuery = new ServprodQuery();
        List<ServprodTable> servprodList = servprodService.selectLists(servprodQuery);
        if(servprodList == null ||servprodList.size() == 0){
            throw new BusinessException(BusinessException.Type.DEFAULT, "服务列表为空");
        }
        for (ServprodTable servprod : servprodList) {
            ShopsServprodTable  shopsServprodTemp= new ShopsServprodTable();
            shopsServprodTemp.setServprodId(servprod.getId())
                             .setServprodName(servprod.getName());

            if(!CommonUtil.isEmpty(shopsServprodList)){
                for (ShopsServprodTable shopsServprodTable : shopsServprodList) {
                    if(servprod.getId() == shopsServprodTable.getServprodId()){
                        shopsServprodTemp.setPrice(shopsServprodTable.getPrice())
                                .setShopsId(shopsServprodTable.getShopsId())
                                .setServtime(shopsServprodTable.getServtime())
                                .setChecked(true);
                    }
                }
            }
            shopsServprodListTemp.add(shopsServprodTemp);
        }


        return shopsServprodListTemp;

    }

    public List<ShopsServprodDTO> getShopsServprodList(ShopsServprodQuery shopsServprodQuery) throws Throwable {

        List<ShopsServprodDTO> shopsServprodListTemp = new ArrayList<>();

        List<ShopsServprodTable> shopsServprodTables = shopsServprodService.selectLists(shopsServprodQuery);

        if(CommonUtil.isEmpty(shopsServprodTables)){
            throw new BusinessException(BusinessException.Type.DEFAULT, "服务列表为空");
        }

        for (ShopsServprodTable shopsServprodTable : shopsServprodTables) {
            ShopsServprodDTO shopsServprodDTO = new ShopsServprodDTO();
            BeanUtils.copyProperties(shopsServprodTable,shopsServprodDTO);
            shopsServprodDTO.setPrice(AmountUtils.changeF2Y(shopsServprodTable.getPrice()));
            shopsServprodListTemp.add(shopsServprodDTO);
        }
        return shopsServprodListTemp;
    }

    public int createShopsServprod(ShopsServprodTable shopsServprodTable) throws Throwable {
        return shopsServprodService.insert(shopsServprodTable);
    }

    @Transactional
    public int modifyShopsServprod(ShopsServprodQuery shopsServprodQuery,List<ShopsServprodTable> shopsServprodList) throws Throwable {

        //查询服务有没有修改
        List<ShopsServprodTable> shopsServprodTables = shopsServprodService.selectLists(new ShopsServprodQuery().setShopsId(shopsServprodQuery.getShopsId()));
        List<String> oldServiceStrList = new ArrayList<>();
        if(!CommonUtil.isEmpty(shopsServprodTables)){
            for(ShopsServprodTable servprod:shopsServprodTables){
                StringBuffer buffer = new StringBuffer();
                buffer.append(servprod.getServprodId()).append(",")
                        .append(servprod.getPrice()).append(",")
                        .append(servprod.getServtime());
                oldServiceStrList.add(buffer.toString());
            }
            List<String> newServiceStrList = new ArrayList<>();
            for(ShopsServprodTable servprod:shopsServprodList){
                StringBuffer buffer = new StringBuffer();
                buffer.append(servprod.getServprodId()).append(",")
                        .append(servprod.getPrice()).append(",")
                        .append(servprod.getServtime());
                newServiceStrList.add(buffer.toString());
            }
            if(CheckDiffListUtils.getDiffrent(oldServiceStrList,newServiceStrList)){
                throw new BusinessException(BusinessException.Type.DEFAULT, "未改动");
            }
        }

        List<String> newServprodId = new ArrayList<>();
       for (ShopsServprodTable shopsServprodTablenew : shopsServprodList) {
           newServprodId.add(String.valueOf(shopsServprodTablenew.getServprodId()));
       }

        ShopsServprodTable shopsServprodTable = new ShopsServprodTable();
        //删除原数据
        if(!CommonUtil.isEmpty(shopsServprodQuery.getShopsId())){
            shopsServprodTable.setShopsId(shopsServprodQuery.getShopsId()).setIsDelete(YesNoEnum.YES);

            shopsServprodService.updateAll(shopsServprodTable,shopsServprodQuery);
//            shopsServprodService.delete(shopsServprodTable);
        }

        List<ShopsServprodTable> shopsServprodListTemp = new ArrayList<>();
        //批量插入新数据
        if(shopsServprodList.size() > 0){
            for (ShopsServprodTable shopsServprodTemp : shopsServprodList) {

                shopsServprodTemp.setCode(IdentityUtil.nextId(IdentityUtil.Worker.USER))
                        .setShopsId(shopsServprodQuery.getShopsId());
                shopsServprodListTemp.add(shopsServprodTemp);
            }

            JSONObject shopid = new JSONObject();
            shopid.put("shopid",shopsServprodQuery.getShopsId());
            shopid.put("serviceIds",newServprodId);

            adminFeignService.getChangeShopServprodInfo(shopid.toString());
            int i = shopsServprodService.insertAll(shopsServprodListTemp);
            rabbitMqSender.sendMessage("websocket_transfer_exchange", "websocket_transfer_key",JSON.toJSONString(new WebsocketMessageResponse<>(WORKPAD,shopsServprodQuery.getShopsId()+"" ,null)));
            return i;
        }else{
            return 0;
        }
    }


    //删除
    public int delShopsServprod(Long code) throws Throwable {
        ShopsServprodTable shopsServprodTable = new ShopsServprodTable();
        shopsServprodTable.setCode(code);
        shopsServprodTable.setIsDelete(YesNoEnum.YES);
        int delRes = shopsServprodService.delete(shopsServprodTable);
        if(delRes > 0){
            return delRes;
        }else{
            throw new DataException(DataException.Type.FAIL, "删除失败");
        }
    }

}
